package org.hxzon.demo.java.concurrency;

import java.util.concurrent.CountDownLatch;

public class TestCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch beginSignal = new CountDownLatch(1);
        CountDownLatch endSignal = new CountDownLatch(8);

        for (int i = 0; i < 8; i++) {
            new Thread(new Work(i, beginSignal, endSignal)).start();
        }

        try {
            System.out.println("统一起跑");
            beginSignal.countDown(); //统一起跑
            endSignal.await(); //等待所有运动员到达终点
            System.out.println("所有运动员到达终点，比赛结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Work implements Runnable {
    private final int id;
    private final CountDownLatch beginSignal;
    private final CountDownLatch endSignal;

    public Work(int id, CountDownLatch begin, CountDownLatch end) {
        this.id = id;
        this.beginSignal = begin;
        this.endSignal = end;
    }

    public void run() {
        try {
            System.out.println("work-" + id + "-等待起跑...");
            beginSignal.await();
            System.out.println("work-" + id + "-起跑...");
            System.out.println("work-" + id + "-到达终点");
            endSignal.countDown();
            System.out.println("work-" + id + "-继续干其他事情");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
